#include "OutputAndReceive.h"

#include <iostream>
#include <cstdio>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>

using namespace std;

// 注意确保Python环境可用
static string receive_cmd = "python3 ../src/speechreceiveandoutput/receivePcm.py"; // 读入命令，    //注意路径，这个路径是从build目录看的  // 用"pwd"看看

static string output_cmd = "python3 ../src/speechreceiveandoutput/outputPcm.py"; // 输出命令

static string execPython(const std::string& cmd) {
    std::array<char, 256> buffer{};
    std::string result;

    // 打开管道，执行命令
    std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd.c_str(), "r"), pclose);
    if (!pipe) {
        throw std::runtime_error("popen() failed!");
    }

    // 读取输出
    while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
        result += buffer.data();
    }

    return result;
}

OutputAndReceive::OutputAndReceive() {}

OutputAndReceive::~OutputAndReceive() {}



string OutputAndReceive::receive_voice(){
    std::string output;
    try {
        output = execPython(receive_cmd);
        // std::cout << "Python脚本输出内容:\n" << output << std::endl;
    } catch (const std::exception& ex) {
        std::cerr << "执行Python脚本失败: " << ex.what() << std::endl;
    }
    return output;
}




string OutputAndReceive::output_voice(){
    std::string output;
    try {
        output = execPython(output_cmd);
        // std::cout << "Python脚本输出内容:\n" << output << std::endl;
    } catch (const std::exception& ex) {
        std::cerr << "执行Python脚本失败: " << ex.what() << std::endl;
    }
    return output;
}


